<template>
    <p>钱包余额:{{ wallet }}</p>
    <el-input v-model="input" style="width: 240px" placeholder="药品编号 例：YP001" />
    <el-button type="primary" @click="inquire">查询</el-button>

    <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <!-- <el-table-column property="id" label="药品编号" width="120" /> -->
        <el-table-column property="drugname" label="药品名称" show-overflow-tooltip />
        <el-table-column property="quantity" label="药品数量" show-overflow-tooltip />
        <!-- <el-table-column property="drugdetail" label="功效" width="120" /> -->
        <el-table-column property="price" label="价格" show-overflow-tooltip />

        <!-- <el-table-column label="数量">
            <template #default="scope">
                <el-input-number v-model="num[scope.$index]" :min="1" :max="1000"
                    @change="addNumbe(scope.$index, scope.row)" />
            </template>
</el-table-column> -->


        <!-- 操作 -->
        <el-table-column label="操作">
            <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.$index, scope.row)">查看</el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <p>总价:{{ totalPrice }}</p>
    <div style="margin-top: 20px">
        <el-button @click="settleAccounts([tableData[1], tableData[2]])">结算</el-button>
        <!-- <el-button @click="toggleSelection()">加入购物车</el-button> -->
    </div>

</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { ElTable, ElMessage } from 'element-plus'
import axios from 'axios';
import { id } from 'element-plus/es/locale/index.mjs';
const wallet: number = 1000;

interface User {
    id: number
    code: string
    drugdetail: string
    drugname: string
    price: string
    quantity: string
    drugld: number
}

const input = ref("")
const num = ref([]);
const tableData = ref([]);
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<User[]>([])
const totalPrice = ref(0);//总价

// 模糊查询
const inquire = () => {
    axios({
        method: "post",
        url: `http://localhost:8080/findme`,
        headers: {
            "Content-Type": "application/json",
        },
        data: { code: input.value },
    }).then((res) => {
        console.log(res)
        tableData.value = res.data.data;
        num.value = res.data.data.map(i => 1);
    }).catch((err) => {
        console.log(
            "err.response.data",
            err.response,
            err.response.data,
            err.response.data.data,
            err.response.data.msg
        );
    });
}

// 判断钱包余额是否足够
const settleAccounts = (rows?: User[]) => {
    const totalCost = totalPrice.value;
    if (totalCost > wallet) {

        ElMessage({
            message: '结算失败余额不足',
            type: 'error',
        })
    } else {

        toggleSelection();
    }
}

//结算
const toggleSelection = (rows?: User[]) => {
    // 这样才能获取到数据
    // console.log(multipleSelection.value)
    // 根据时间生成订单编号
    const code = generateTimestamp("DD-");

    // 将数据整理，调用结算接口
    multipleSelection.value.forEach(item => {

        // 整理后端需要的数据
        const dataList = {
            drugId: item.drugld,
            code: code,
            name: item.drugname,
            number: item.quantity
        }
        console.log(dataList)

        axios({
            method: "post",
            url: `http://localhost:8080/insertOrders`,
            headers: {
                "Content-Type": "application/json",
            },
            data: dataList,
        }).then((res) => {
            console.log(res);
        }).catch((err) => {
            console.log(
                "err.response.data",
                err.response,
                err.response.data,
                err.response.data.data,
                err.response.data.msg
            );
        });
    })

    ElMessage({
        message: '结算成功',
        type: 'success',
    })
}


// 复选框勾选数据
const handleSelectionChange = (selection: User[]) => {
    // 这个是复选框数据不要删除
    multipleSelection.value = selection
    //计算总价 
    let total = 0;
    selection.forEach(item => {
        total += parseFloat(item.price) * parseFloat(item.quantity);
    });
    totalPrice.value = parseFloat(total.toFixed(2)); // 根据需要调整精度
}



const addNumbe = (index: number, row: User) => {

}

// 查看
const handleEdit = (index: number, row: User) => {
    console.log(index, row)
}

// 删除
const handleDelete = (row: User) => {
    console.log(row.id)
    axios({
        method: "post",
        url: `http://localhost:8080/delShopping`,
        headers: {
            "Content-Type": "application/json",
        },
        data: { id: row.id },
    }).then((res) => {
        location.reload();
        console.log(res);
    }).catch((err) => {
        console.log(
            "err.response.data",
            err.response,
            err.response.data,
            err.response.data.data,
            err.response.data.msg
        );
    });
}


// 生成订单编号
const generateTimestamp = (name: string) => {
    const date = new Date()
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    const milliseconds = String(date.getMilliseconds()).padStart(3, '0')

    return `${name}${year}${month}${day}${hours}${minutes}${seconds}${milliseconds}`
}

// 初始化数据
const initData = () => {
    axios({
        method: "get",
        url: `http://localhost:8080/selshop`,
        headers: {
            "Content-Type": "application/json",
        },
        data: {},
    }).then((res) => {
        // console.log(res)
        tableData.value = res.data;
        num.value = res.data.data.map(i => 1);
    }).catch((err) => {
        console.log(
            "err.response.data",
            err.response,
            // err.response.data,
            // err.response.data.data,
            // err.response.data.msg
        );
    });
}
initData();
</script>
